<?php
/**
 * DownGoods.php class file.
 * @author wudg <544038230@qq.com>
 * @date 2020/12/27- 下午5:40
 */

namespace common\jobs\sync;


use common\constants\DefaultConst;
use common\constants\ProductConst;
use common\constants\SyncConst;
use common\dao\PddSyncLogDao;
use common\exception\ValidatorException;
use common\models\PddMallLogistics;
use common\services\SyncService;
use common\components\api\isv\Goods;
use common\exception\ServicesException;
use common\exception\JobException;
use console\components\helpers\ConsoleHelper;
use Yii;
use yii\db\Exception;

class SyncGoodsToLogistics extends SyncBase implements \common\drivers\interfaces\JobInterface
{
    public $args = [];


    public function __construct(array $args = [])
    {

        $this->args = $args;
        $this->cacheSuccessKey .= $this->args['log_id'];
        $this->cacheErrorKey .= $this->args['log_id'];
        $this->totalCacheKey .= $this->args['log_id'];
    }


    /**
     * 处理队列
     * @return mixed|void
     */
    public function handle() :void
    {
        //在售商品同步
        $priRequest = [
            'page' =>1,
            'page_size' =>20
        ];

        try {
            Yii::$app->db->open();
            do{
                $logisticsList = (new Goods())->pddGoodsLogisticsTemplateGet($priRequest,$this->args['mall_id']);

                $totalLogistics = $logisticsList['total_count'];
                Yii::$app->redis->setex($this->totalCacheKey,86400,$totalLogistics);
                if(isset($logisticsList['logistics_template_list']) && count($logisticsList['logistics_template_list'])) {
                    foreach ($logisticsList['logistics_template_list'] as $k => $logistics)
                    {
                        $insertLogistics = [];
                        $insertLogistics['mall_id'] = $this->args['mall_id'];
                        $insertLogistics['uid'] = $this->args['uid'];
                        $insertLogistics['template_id'] = $logistics['template_id'];
                        $insertLogistics['province_id'] = $logistics['province_id'] ?? 0;
                        $insertLogistics['sf_free_type'] = $logistics['sf_free_type'];
                        $insertLogistics['cost_type'] = $logistics['cost_type'];
                        $insertLogistics['status'] = DefaultConst::IS_NORMAL;
                        $insertLogistics['district_id'] = $logistics['district_id'] ?? 0;
                        $insertLogistics['city_id'] = $logistics['city_id'] ?? 0;
                        $insertLogistics['template_name'] = $logistics['template_name'] ?? '-';
                        $insertLogistics['cost_template_list'] = json_encode($logistics['free_deliver_house_area_list'],JSON_UNESCAPED_UNICODE);
                        $insertLogistics['free_province_list'] = json_encode($logistics['free_province_list'],JSON_UNESCAPED_UNICODE);
                        $insertLogistics['sync_at'] = time();
                        $result =  (new SyncService())->syncLogistics($insertLogistics);

                        if($result)
                        {
                            $this->setSuccessNum();
                            ConsoleHelper::runInfo('成功商品运费模板template_id:'.$logistics['template_id']);
                        }else{
                            $this->setErrorNum();
                        }
                    }

                }else{
                    break;
                }

            }while(count($logisticsList['logistics_template_list']) >= $priRequest['page_size']);

            Yii::$app->db->close();
        }catch (ValidatorException $e)
        {
            $this->setErrorNum();
            throw new JobException($e->getMessage());
        }catch (ServicesException $e)
        {
            $this->setErrorNum();
            throw new JobException($e->getMessage());
        }catch (Exception $e)
        {
            $this->setErrorNum();
            throw new JobException($e->getMessage());
        } finally {
            Yii::$app->db->close();
        }
    }

    protected function setSuccessNum()
    {
        $cacheSuccessNum = Yii::$app->redis->get($this->cacheSuccessKey);
        if(!$cacheSuccessNum)
        {
            Yii::$app->redis->setex($this->cacheSuccessKey,86400,1);
        }else{
            Yii::$app->redis->incr($this->cacheSuccessKey);
        }
        $this->upsetBatchInfo();
    }

    protected function getSuccessNum()
    {
        return  Yii::$app->redis->get($this->cacheSuccessKey);
    }


    protected function setErrorNum()
    {
        $cacheErrorNum = Yii::$app->redis->get($this->cacheErrorKey);
        if(!$cacheErrorNum)
        {
            Yii::$app->redis->setex($this->cacheErrorKey,86400,1);
        }else{
            Yii::$app->redis->incr($this->cacheErrorKey);
        }
        $this->upsetBatchInfo();
    }


    protected function getErrorNum()
    {
        return  Yii::$app->redis->get($this->cacheErrorKey);
    }


    protected function upsetBatchInfo()
    {
        $successNum = (int)$this->getSuccessNum();
        $errorNum = (int)$this->getErrorNum();
        $totalNum = $successNum + $errorNum;

        $total_cnt = Yii::$app->redis->get($this->totalCacheKey);
        if($totalNum == $total_cnt)
        {

            $syncLog = (new PddSyncLogDao())->getInfoByPk($this->args['log_id']);
            $syncLog->suc_cnt = $successNum;
            $syncLog->total_cnt = $total_cnt;
            $syncLog->err_cnt = $errorNum;
            $syncLog->status = SyncConst::SYNC_STATUS_YES;
            $syncLog->save();

            //历史同步的全部设置为删除状态
            PddMallLogistics::updateAll(['status' => DefaultConst::IS_DEL],'mall_id = '.$this->args['mall_id'].' AND uid = '.$this->args['uid'].' AND sync_at < '.$syncLog->sync_at);
            Yii::$app->redis->del($this->cacheErrorKey);
            Yii::$app->redis->del($this->totalCacheKey);
            Yii::$app->redis->del($this->cacheSuccessKey);
        }
    }
}